<?php

/**
 * SmartPHP framework
 *
 * @name SmartPHP framework
 * @package SmartPHP
 * @author 费尔 <admin@smartphp.cn>
 * @version 1.0 Beta
 * @link http://www.smartphp.cn
 * @copyright smartphp.cn
 * @license <a href="http://www.smartphp.cn">smartphp</a>
 */

namespace Base;

/**
 * URL类
 * @author 费尔
 */
class Url {

    /**
     * 解析URL
     * @param string $url
     * @param array $params
     * @return string
     */
    public static function parse($url, $params = []) {
        if (preg_match('/^(?:http(?:s)?:\/\/(?:[\w-]+\.)+[\w-]+(?:\:\d+)*+(?:\/[\w- .\/?%&=]*)?)$/', $url))
            return $url;
        $array = parse_url($url);


        if (isset($array['fragment'])) { // 解析锚点
            $anchor = $array['fragment'];
            if (false !== strpos($anchor, '?')) { // 解析参数
                list($anchor, $array['query']) = explode('?', $anchor, 2);
            }
            if (false !== strpos($anchor, '@')) { // 解析域名
                list($anchor, $host) = explode('@', $anchor, 2);
            }
        }

        //$app = self::parseName(($array['scheme'] ?? APP_NAME), true);
        if (empty($array['path']) || strpos($array['path'], '/') === false)
            $array['path'] = APP_CONTROLLER . '/' . (!empty($array['path']) ? $array['path'] : APP_ACTION) . (Config::get('url.htmlsuffix') ? '.' . Config::get('url.htmlsuffix') : '');
        $domain = $_SERVER['HTTP_HOST'];
        if (isset($array['scheme'])) {
            //print_r($array);
            $domain = $domain === 'localhost' ? 'localhost' : strtolower($array['scheme']) . strstr($domain, '.');
        }

        $url = !empty($array['path']) ? $array['path'] : APP_CONTROLLER . '/' . APP_ACTION . (Config::get('url.htmlsuffix') ? '.' . Config::get('url.htmlsuffix') : '');
        if (isset($array['query'])) {
            parse_str($array['query'], $query);
            $params = array_merge($query, $params);
            $str = '/';
            $depr = '/';
            foreach ($params as $var => $val)
                $str .= $var . $depr . $val . $depr;
            $url .= substr($str, 0, -1);
        }
        $url = trim($url, '/');

        if (isset($anchor)) {
            $url .= '#' . $anchor;
        }
        if ($domain) {
            $url = (Request::isSsl() ? 'https://' : 'http://') . $domain . '/' . $url;
        }

        return $url;
    }

}
